import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.Random;


public class SlaveListener extends Thread {

	DatagramSocket ds = null;
	public final static int PORT = 8765;
	ISlave messageHandler = null;
	boolean keepRunning = true;
	String IP = "141.212.110.104";
	String ID = "slave1";
	String MASTER_IP = "141.212.110.104";
	Random r = new Random();
	
	public SlaveListener(ISlave slave) {
		try {
			ds = new DatagramSocket(PORTS.SLAVE_LISTENER_PORT_FOR_MASTER + r.nextInt(1000));
			messageHandler = slave;
		} 
		catch (SocketException e) {
			e.printStackTrace();
			keepRunning = false;
		}
	}
	
	public void notifyMaster(int port) throws SocketException, IOException
	{
		IMessage msg = new Message();
		msg.setMessageID(IMessage.MESSAGE_FROM_SLAVE);
		msg.setKey(new DataObject(IP.getBytes()));
		msg.setValue(new DataObject(new Integer(port).toString().getBytes()));
		byte[] serializedData = msg.serialize();
		ds.send(new DatagramPacket(serializedData, serializedData.length, new InetSocketAddress(MASTER_IP, PORTS.MASTER_LISTENER_PORT_FOR_SLAVE)));
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(keepRunning){
			byte[] buf = new byte[256];        
	        DatagramPacket packet = new DatagramPacket(buf, buf.length);
	        try {
				ds.receive(packet);
			} 
	        catch (IOException e) {
	        	keepRunning = false;
				e.printStackTrace();
			}
	        IMessage message = new Message();
	        message.deserialize(buf);
	        message.setMessageID(IMessage.MESSAGE_FROM_MASTER);
	        messageHandler.handleMessage(message);
		}
	}
}
